/* Copyright (c) 2015 Slava Naumenko - http://m4w.codeplex.com */

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Runtime.InteropServices;

namespace M4W.TJ.RunSiteWorkflows
{
    [Guid("d7aa0af1-0d3e-44f9-adc4-28b0d76360ca")]
    public class CreateDeleteTimerJob : SPFeatureReceiver
    {
        private const string JobName = "M4W.TJ.RunSiteWorkflows";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            if (!IsJobCreated(site, JobName))
            {
                // Create Timer Job

                SPDailySchedule schedule = new SPDailySchedule();
                schedule.BeginHour = 3;
                schedule.EndHour = 8;

                //SPHourlySchedule schedule = new SPHourlySchedule();
                //schedule.BeginMinute = 0;
                //schedule.EndMinute = 59;

                //SPMinuteSchedule schedule = new SPMinuteSchedule();
                //schedule.BeginSecond = 0;
                //schedule.EndSecond = 59;
                //schedule.Interval = 5;

                RunSiteWorkflowsTJ runSiteWorkflowsJob = new RunSiteWorkflowsTJ(JobName, site.WebApplication);
                runSiteWorkflowsJob.Schedule = schedule;
                runSiteWorkflowsJob.Update();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            // Delete Job

            if (!IsFeatureUsed(site))
            {
                foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                {
                    if (job.Name == JobName)
                    {
                        job.Delete();
                    }
                }
            }
        }

        private bool IsJobCreated(SPSite site, string name)
        {
            bool rval = false;
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == name)
                {
                    rval = true;
                    break;
                }
            }
            return rval;
        }

        private bool IsFeatureUsed(SPSite csite)
        {
            Guid featureId = new Guid("c3dfa07f-7117-40e2-835a-c133b4dda1e0");

            bool rval = false;
            foreach (SPSite ssite in csite.WebApplication.Sites)
            {
                if (ssite.Features[featureId] != null && ssite.ID != csite.ID)
                {
                    rval = true;
                    break;
                }
            }
            return rval;
        }
    }
}
